package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

class MyClient {
    private int size = 1024;

    private ByteBuffer byteBuffer;


    private SocketChannel socketChannel;

    public void connect() throws IOException {
        socketChannel = SocketChannel.open();

        socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999));

        socketChannel.configureBlocking(false);

        byteBuffer = ByteBuffer.allocate(size);


        receive();
    }

    private void receive() throws IOException {
        while (true) {
            byteBuffer.clear();
            int count;

            // 如果没有数据，则阻塞一直到有数据
            while ((count = socketChannel.read(byteBuffer)) > 0) {
                byteBuffer.flip();

                while (byteBuffer.hasRemaining()) {
                    System.out.println((char) byteBuffer.get());
                }

                send2Server("say hi".getBytes());
            }
        }

    }

    private void send2Server(byte[] bytes) throws IOException {

        byteBuffer.clear();
        byteBuffer.put(bytes);
        byteBuffer.flip();
        socketChannel.write(byteBuffer);

    }

    public static void main(String[] args) throws IOException {
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                try {
                    new MyClient().connect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();

        }
    }

}
